package com.qfedu.vhr.framework.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author baize
 * @date 2023/1/9
 * @site www.qfedu.com
 */
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {
    /**
     * 判断当前用户是否具备所需要的角色
     *
     * @param authentication   当前用户信息在这里
     * @param object           这个其实就是 com.qfedu.vhr.framework.config.MyFilterInvocationSecurityMetadataSource#getAttributes(java.lang.Object) 方法的参数
     * @param configAttributes 这个其实就是 com.qfedu.vhr.framework.config.MyFilterInvocationSecurityMetadataSource#getAttributes(java.lang.Object) 方法的返回值
     * @throws AccessDeniedException               如果这个方法顺利执行，没有抛出异常，表示用户具备当前请求所需要的角色；如果抛出异常，则说明用户权限不足
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        //获取当前用户所具备的角色
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (ConfigAttribute configAttribute : configAttributes) {
            String attribute = configAttribute.getAttribute();
            if ("ROLE_LOGIN".equals(attribute)) {
                //查看当前用户是否已经认证
                if (!(authentication instanceof AnonymousAuthenticationToken)) {
                    //说明当前用户已经认证了
                    return;
                } else {
                    //说明当前用户没有登录
                    throw new AccessDeniedException("权限不足，请联系管理员");
                }
            }
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(attribute)) {
                    //说明当前用户具备当前请求所需要的某一个角色
                    return;
                }
            }
        }
        //如果执行到这一句，说明当前请求所需要的角色当前用户并不具备
        throw new AccessDeniedException("权限不足，请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
